package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client3 {
    private Socket socket;

    public Client3(){
        try {
            System.out.println("正在启动客户端....");
            socket = new Socket("localhost",8091);
            System.out.println("客户端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        /*
            写东西给服务器....
         */
        try {
            ServerHeadler serverHeadler = new ServerHeadler();
            Thread t = new Thread(serverHeadler);
            t.setDaemon(true); //设置为守护线程，也就意味着当所有普通线程结束时，才会停止读取服务端发送过来的消息
            t.start();

            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(),"UTF-8"
                            )
                    )
            ,true);
            Scanner scanner = new Scanner(System.in);
            System.out.println("可以写入....");
            while (true){
                String line = scanner.nextLine();
                if ("exit".equals(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private class ServerHeadler implements Runnable{
        @Override
        public void run() {
            //输出流，用于读取服务端发送过来的消息
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String message;
                while (true){
                    message = br.readLine();
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client3 client3 = new Client3();
        client3.start();
    }
}
